package org.ssp.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class SignUtil {
	public static String token="weixin";
	
	public static boolean checkSinature(String signature,String timestamp,String nonce){
		System.out.println("enter the function checkSinature");
		boolean result=false;
		
		//按字典排序
		String[] array=new String[]{token,timestamp,nonce};
		Arrays.sort(array);
		//拼接
		String str=array[0].concat(array[1]).concat(array[2]);
		
		//hash加密
		String shastr=null;
		try {
			MessageDigest md=MessageDigest.getInstance("SHA-1");
			byte[] digest=md.digest(str.getBytes());
			shastr=byte2str(digest);
			
			
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("加密后的字串是"+shastr);
		if(shastr!=null&&shastr.equals(signature)){
			result=true;
		}
		return result;
		
	}
	/**
	 * 将字节数组专程为十六进制字符串
	 * 
	 * @param array
	 * @return
	 */
	public static String byte2str(byte[] array){
		StringBuffer hexstr=new StringBuffer();
		String shaHex="";
		for(int i=0;i<array.length;i++){
			shaHex=Integer.toHexString(array[i]&0xff);
			if(shaHex.length()<2){
				hexstr.append(0);
			}
			hexstr.append(shaHex);
		}
		return hexstr.toString();
		
	}

}
